import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from '@angular/router';
import { StorageService } from '../providers';

@Injectable({
  providedIn: 'root',
})
export class LoginGuard implements CanActivate {
  constructor(private router: Router, private storage: StorageService) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | UrlTree {
    // 获取缓存的 token 数据，并根据其值决定是否可以继续访问
    const token = this.storage.get('access_token');
    if (token) {
      // 继续访问
      return true;
    } else {
      // 拒绝访问并返回路由 UrlTree，使路由跳转回登录页
      return this.router.parseUrl('/auth/login');
    }
  }
}
